package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理类
 *
 * @author Mylinja 2021-12-15 星期三 14:43
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * SQLIntegrityConstraintViolationException异常处理方法
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> SQLIntegrityConstraintViolationExceptionHandler(SQLIntegrityConstraintViolationException e) {
        log.error(e.getMessage());
        if (e.getMessage().contains("Duplicate entry")) {
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    /**
     * customException自定义异常处理方法
     */
    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(CustomException e) {
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }

    /**
     * FileSizeLimitExceededException异常处理方法
     */
    @ExceptionHandler(FileSizeLimitExceededException.class)
    public R<String> fileSizeLimitExceededExceptionHandler(FileSizeLimitExceededException e) {
        log.error(e.getMessage());
        return R.error("文件大小不能超过100Mb");
    }

    /**
     * FileNotFoundException异常处理方法
     * 处理图片显示异常
     */
    @ExceptionHandler(FileNotFoundException.class)
    public void fileNotFoundExceptionHandler(FileNotFoundException e) {
        log.error(e.getMessage());
        log.error("图片无法展示");
    }

}
